<?php
import('@.Action.PublicAction');
class CodeAction extends Action
{
    function _initialize() 
    {
       if(!isset($_SESSION['user_right'])) {
			$this->redirect('login','Public');
        }
        parent::_initialize();
    }
    	
	function index()
	{
		if(isset($_SESSION["COMMENTID"])) $_GET["ID"]=$_SESSION["COMMENTID"];
		$Dao = D("Comment");
		$vo = $Dao->find("ID=".$_GET["ID"]);
		if($vo === false) 
		{ 
			$this->assign("jumpUrl",__URL__); 
			$this->error("不存在记录！"); 
		} else{
			if($vo['ISCODE']!="1"){
				$this->assign("jumpUrl",__URL__); 
				$this->error("该字段不是代码！"); 			
			}else{
				if($vo['RELID']=="0"){
					$this->assign("jumpUrl",__URL__); 
					$this->error("该字段不是代码具体的管理！"); 			
				}else{
					$_SESSION["COMMENTID"]=$_GET["ID"];
					$this->assign("vo",$vo); 
					$Code = D("Code");
					$voList	= $Code->findAll("COMMENTID=".$_GET["ID"]);
					$this->assign("list",$voList);
					$this->display();
				}
			}
		}
	}
	

    /**
     +----------------------------------------------------------
     * 默认删除操作
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    public function delete()
    {
        //删除指定记录
        $model        = D('Code');
        if(!empty($model)) {
            $id         = $_REQUEST['id'];
            if(isset($id)) {
                if($model->delete($id)){
                    $this->success(L('_DELETE_SUCCESS_'));
                }else {
                    $this->error(L('_DELETE_FAIL_'));
                }        	
            }else {
                $this->error('非法操作');
            }        	
        }
    }

    /**
     +----------------------------------------------------------
     * 默认添加操作
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
	function add() 
	{
		// 添加内容的页面 
		$this->display(); 
	} 

	function insert() 
	{ 
		// 保存添加的数据
		$Dao = D("Code"); 
		$vo = $Dao->create(); 
		if(false === $vo) { 
	 		$this->error($Dao->getError()); 
		} 
 
		$rs = $Dao->add(); 
		if($rs){ 
			$this->assign("jumpUrl",__URL__); 
			$this->success("添加数据成功!"); 
		}else{ 
			$this->error("添加数据失败"); 
		} 
	}
    /**
     +----------------------------------------------------------
     * 默认编辑操作
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
	function edit() 
	{ 
		// 编辑页面 
		$Dao = D("Code"); 
		$vo = $Dao->find("CODEID=".$_GET["id"]); 
		if($vo === false) 
		{ 
			$this->assign("jumpUrl",__URL__); 
			$this->error("Non-existed record"); 
		} 
		 
		$this->assign("vo",$vo); 
		$this->display(); 
	} 
	
	function update() 
	{ 
		// 保存编辑过的数据 
		$Dao = D("Code"); 
		$vo = $Dao->create("","edit");
		if(false === $vo) { 
	 		$this->error($Dao->getError()); 
		} 
 
		$rs = $Dao->save(); 
		if($rs){ 
			$this->assign("jumpUrl",__URL__); 
			$this->success("保存修改成功!"); 
		}else{ 
			$this->error("保存修改失败"); 
		} 
	}
    /**
     +----------------------------------------------------------
     * 批量导入操作
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */	
    //入口上传文件index	
	function importIndex()
	{
		$this->display();
        return;
	}
	// 文件上传
    protected function _upload() 
    {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize  = 329220000 ;
        //设置上传文件类型
        $upload->allowExts  = explode(',','dbf');
        //设置附件上传目录
        $upload->savePath =  '../Public/Uploads/'; 

        //执行上传操作
        if(!$upload->upload()) {
            if($this->isAjax() && isset($_POST['_uploadFileResult'])) {
                $uploadSuccess =  false;
                $ajaxMsg  =  $upload->getErrorMsg();
            }else {
                //捕获上传异常
                $this->error($upload->getErrorMsg());            	
            }
        }else{
			$uploadSuccess	=	true;
		}
        // 判断是否有Ajax方式上传附件
        // 并且设置了结果显示Html元素
        if($this->isAjax() && isset($_POST['_uploadFileResult']) ) {
            // Ajax方式上传参数信息
            $info = Array();
            $info['success']  =  $uploadSuccess;
            $info['message']   = $ajaxMsg;
			$info['info']=$upload->getUploadFileInfo();            
            //设置Ajax上传返回元素Id
            $info['uploadResult'] =  $_POST['_uploadFileResult']; 
            if(isset($_POST['_uploadFormId'])) {
                //设置Ajax上传表单Id
                $info['uploadFormId'] =  $_POST['_uploadFormId']; 
            }
            if(isset($_POST['_uploadResponse'])) {
                //设置Ajax上传响应方法名称
                $info['uploadResponse'] =  $_POST['_uploadResponse']; 
            }

            $this->ajaxUploadResult($info);
        }
        return ;
    }

    protected function ajaxUploadResult($info) 
    {
        // Ajax方式附件上传提示信息设置
        // 默认使用mootools opacity效果
        $show   = '<script language="JavaScript" src="'.WEB_PUBLIC_URL.'/Js/mootools.js"></script><script language="JavaScript" type="text/javascript">'."\n";    
        $show  .= ' var parDoc = window.parent.document;';    
        $show  .= ' var result = parDoc.getElementById("'.$info['uploadResult'].'");';   
        if(isset($info['uploadFormId'])) {
   	        $show  .= ' parDoc.getElementById("'.$info['uploadFormId'].'").reset();';
        }
        $show  .= ' result.style.display = "block";';   
        $show .= " var myFx = new Fx.Style(result, 'opacity',{duration:600}).custom(0.1,1);";
        if($info['success']) {
            // 提示上传成功
            $show .=  'result.innerHTML = "<div style=\"color:#3333FF\">文件上传成功！</div>";';
            $url="http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF'];
			$show .= 'window.parent.location="'.str_replace("index.php","index.php/Code/selectField",$url).'";'; 
			$_SESSION["dbffile"]=$info['info'][0]['savename'];        
            // 如果定义了成功响应方法，执行客户端方法
            // 参数为上传的附件id，多个以逗号分割
            if(isset($info['uploadResponse'])) {
                $show  .= 'window.parent.'.$info['uploadResponse'].'();';
            }
        }else {
            // 上传失败
            // 提示上传失败
            $show .=  'result.innerHTML = "<div style=\"color:#FF0000\">上传失败：'.$info['message'].'</div>";';           	
        }
        $show .= "\n".'</script>';   
        $this->assign('_ajax_upload_',$show);   
        return ;
   	}	
	//文件上传
	public function upload() {
		if(!empty($_FILES)) {
			//如果有文件上传 上传附件
			$this->_upload();
			$this->forward();
		}
		echo str_replace("/Index/","/dbf/",$REQUEST_URI);
		$str= "http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF'];
		echo str_replace("/upload/","/dbf/",$str);
	}
	
	
	//字段选择
	public function selectField(){
		import("ORG.Io.Dbf");
		$dbf=new readdbf("../Public/Uploads/".$_SESSION["dbffile"],1);

		$vo[]=array('COMMENT'=>'父级代码','FIELD'=>'PCODE','DBFNAME'=>'PCODE');
		$vo[]=array('COMMENT'=>'代码','FIELD'=>'CODE','DBFNAME'=>'CODE');
		$vo[]=array('COMMENT'=>'代码名称','FIELD'=>'CODENAME','DBFNAME'=>'CODENAME');
		foreach($vo as $tmp){
			$field[]=array(
			"name"=>$tmp['COMMENT'],
			"field"=>$tmp['FIELD'],
			"dbfname"=>$tmp['DBFNAME'],
			"dbf"=>$dbf->fieldname,
			);	
		}
		//dump($field);
		//exit();
		$this->assign("field",$field);
		$this->display();
	}
	//数据导入html
	public function import(){
		$_SESSION["PostData"]=$_POST;
		$this->display();	
	}

	// 数据导入操作
	public function query() {
		/*发送响应*/
		header('Content-Type: text/html; charset=UTF-8');
		/*导入关联文件*/
		import("ORG.Io.Dbf");
		$Model = new Model(); // 实例化一个model对象 没有对应任何数据表
		$tableName=C('DB_PREFIX')."code";
		$dbf=new readdbf("../Public/Uploads/".$_SESSION["dbffile"],1);
		$arr=$dbf->read();
		$_POST=$_SESSION["PostData"];
		$_POST['COMMENTID']=$_SESSION['COMMENTID'];
		unset($_POST['think_html_token']);
		$i=0;
		foreach ($arr as $tmp){
			$str="";
			$str.="INSERT INTO `".$tableName."` (";
			foreach ($_POST as $key=>$vo){
				$str.="`".$key."`,";
			}
			$str=substr($str,0,strlen($str)-1);
			$str.=") VALUES (";
			foreach ($_POST as $key=>$vo){
				if($key=="COMMENTID"){
					$str.="'".$_POST['COMMENTID']."',";
				}else{
					$str.="'".$tmp[$vo]."',";
				}
			}
			$str=substr($str,0,strlen($str)-1);
			$str.=");";
			$Model->execute($str);
			//echo $str."<br>";
			$i++;
			echo "Line:	".$i."<br>";
		}
		//提示！
		echo "<script>alert('数据导入完成!');</script>";
	}		
}
?>